package org.jsbd.boss.task;

import org.apache.commons.beanutils.BeanUtils;
import org.jsbd.boss.common.redis.RedisClient;
import org.jsbd.boss.domian.SimulatorADTask;
import org.jsbd.boss.service.ISimulatorADService;
import org.jsbd.boss.util.ADPoolExecutor;
import org.jsbd.boss.util.CacheKey;
import org.jsbd.boss.util.PropertiesUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.annotation.Resource;
import java.util.Iterator;
import java.util.Random;
import java.util.Set;
import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;

/**
 * 
 * @author zbh
 * 
 */
public class SimulatorYQADTask implements Runnable {

	@Resource
	private ISimulatorADService simulatorADService;
	// 用于判断定时任务是否开启
	private final static String QUARTZ_FLAG_ON = "on";
	// 定时任务开关：默认为off
	private String quartzFlag = PropertiesUtil.getValue("simulator_yqad_flag", "off");

	public static final Logger LOGGER = LoggerFactory.getLogger(SimulatorUVTask.class);
	@Resource
	private RedisClient<String, Object> redisClient;

	private static Random r = new Random();

	private static int TASK_COUNT = 100;

	private static Integer tasktimeout = 30 * 1000;

	public void start() {
		Thread t = new Thread(this);
		t.start();
	}

	@Override
	public void run() {
		String redisKey = CacheKey.YBAD_DELAY_QUEUE;
		if (QUARTZ_FLAG_ON.equalsIgnoreCase(quartzFlag)) {
			while (true) {
				try {
					long expireTime = 3;
					if (redisClient.evalSetNx(redisKey + "_LOCK", expireTime)) {
						int TIME_SEPARATION = new Random().nextInt(45) + 60;
						TIME_SEPARATION = TIME_SEPARATION * 1000;
						Set<Object> setad = redisClient.rangeByScore(redisKey, 0, System.currentTimeMillis()
								- TIME_SEPARATION, 0, TASK_COUNT);
						if (setad != null && setad.size() > 0) {
							try {
								redisClient.removeRange(redisKey, 0, (setad.size() - 1));
								if (LOGGER.isInfoEnabled()) {
									LOGGER.info("队列【" + redisKey + "】拿到需要处理的延时usertoken任务数量【" + setad.size()
											+ "】......");
								}
								for (Iterator<Object> iter = setad.iterator(); iter.hasNext();) {
									SimulatorADTask task = (SimulatorADTask) iter.next();
									final SimulatorADTask taskad = new SimulatorADTask();
									BeanUtils.copyProperties(taskad, task);
									try {

										FutureTask future = new FutureTask(new Callable<Boolean>() {
											public Boolean call() {
												try {
													simulatorADService.simulatorADTask(taskad);
												} catch (Exception e) {
													LOGGER.error("InterruptedException: ", e);
												}
												return null;
											}

										});

										ADPoolExecutor.getPoolExeFuture(future);

										if ("1".equals(task.getPosition())) {
											task.setPosition("3");
											int x = r.nextInt(task.getDvw());
											int y = r.nextInt(task.getDvh());
											task.setDownx(x);
											task.setDowny(y);
											task.setUpx(x);
											task.setUpy(y);			
											redisClient.putZset(CacheKey.YBAD_DELAY_QUEUE, task, System.currentTimeMillis());
										}
									} catch (Exception e) {
										LOGGER.error("", e);
									}
								}

							} catch (Exception e) {
								LOGGER.error("", e);
							}
						}

					}
				} catch (Exception e) {
					LOGGER.error("", e);
				}
				try {
					// logger.info("今天已经执行了+total+");
					Thread.sleep(500);
				} catch (InterruptedException e) {
					LOGGER.error("", e);
				}
			}
		}
	}

	public String getQuartzFlag() {
		return quartzFlag;
	}

	public void setQuartzFlag(String quartzFlag) {
		this.quartzFlag = quartzFlag;
	}

	public static String getQuartzFlagOn() {
		return QUARTZ_FLAG_ON;
	}

}
